package com.zprmb.udzt.beifen;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.growingio.android.sdk.collection.GrowingIO;
import com.squareup.picasso.Picasso;
import com.zprmb.udzt.BbtApplication;
import com.zprmb.udzt.GeActivity;
import com.zprmb.udzt.MainActivity;
import com.zprmb.udzt.R;
import com.zprmb.udzt.SplashActivity;
import com.zprmb.udzt.V6LoginActivity;
import com.zprmb.udzt.alert.AlertView;
import com.zprmb.udzt.alert.OnDismissListener;
import com.zprmb.udzt.alert.OnItemClickListener;
import com.zprmb.udzt.gesture.GestureContentView;
import com.zprmb.udzt.gesture.GestureDrawline.GestureCallBack;
import com.zprmb.udzt.gesture.GestureEditActivity;
import com.zprmb.udzt.gesture.GestureVerifyActivity;
import com.zprmb.udzt.http.AjaxParams;
import com.zprmb.udzt.util.BitmapUtils;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.CustomDialog_view;
import com.zprmb.udzt.util.FingerSetting;
import com.zprmb.udzt.util.FingerprintUtil;
import com.zprmb.udzt.util.VolleryUtil;
import com.zprmb.udzt.util.VolleryUtil3;
import com.zprmb.udzt.view.RoundImageView;

import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * ���ƻ���/У�����
 */
public class GestureVerifyActivity_BeiFen extends GeActivity implements View.OnClickListener, OnItemClickListener, OnDismissListener {
    /**
     * �ֻ����
     */
    public static final String PARAM_PHONE_NUMBER = "PARAM_PHONE_NUMBER";
    /**
     * ��ͼ
     */
    public static final String PARAM_INTENT_CODE = "PARAM_INTENT_CODE";
    private RelativeLayout mTopLayout;
    private TextView mTextTitle;
    private TextView mTextCancel;
    private ImageView mImgUserLogo;
    private TextView mTextPhoneNumber;
    private TextView mTextTip;
    private AlertView mAlertView;
    private int error = 0;
    private String csrf;
    private FrameLayout mGestureContainer;
    private GestureContentView mGestureContentView;
    private TextView mTextForget;
    private TextView mTextOther;
    private String mParamPhoneNumber;
    private long mExitTime = 0;
    private int mParamIntentCode;
    private SharedPreferences sha;
    private TextView text_welcome;
    private RoundImageView user_logo;
    private TelephonyManager tm;
    private CustomDialog_view.Builder builder;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gesture_verify);
        setImmersionStatus();
        BbtApplication.getInstance().addActvity(this);
        ObtainExtraData();
        setUpViews();
        setUpListeners();

        tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
        if (isFinger()) {
            onFingerprintClick(null);
        }
//		onFingerprintClick(null);
    }

    public void onFingerprintClick(View v) {

        FingerprintUtil.callFingerPrint(new FingerprintUtil.OnCallBackListenr() {

            @Override
            public void onSupportFailed() {
                showToast("当前设备不支持指纹");
            }

            @Override
            public void onInsecurity() {
                FingerSetting.openFingerPrintSettingPage(GestureVerifyActivity_BeiFen.this);
            }

            @Override
            public void onEnrollFailed() {
                showToast("请到设置中设置指纹");
            }

            @Override
            public void onAuthenticationStart() {
                builder = new CustomDialog_view.Builder(GestureVerifyActivity_BeiFen.this);
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        FingerprintUtil.cancel();
                        builder.create().dismiss();
                    }
                });
                builder.setMessage("“优点智投”的 Touch ID");
                builder.setMessage2("请验证已有手机指纹");
                builder.create().setCancelable(false);
                builder.create().show();
            }

            @Override
            public void onAuthenticationError(int errMsgId, CharSequence errString) {
                showToast(errString.toString());
//                Log.e("dialog", builder.create()+"");
                if (builder.create() != null) {
                    builder.create().mdissmis();
                }
            }

            @Override
            public void onAuthenticationFailed() {
                showToast("解锁失败");
            }

            @Override
            public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
                showToast(helpString.toString());
            }

            @Override
            public void onAuthenticationSucceeded(FingerprintManagerCompat.AuthenticationResult result) {
                showToast("解锁成功");
                Log.e("dialog", builder.create() + "");
//                Log.e("object", builder.create()+""+builder.create().isShowing()+"");
                if (builder.create() != null) {
                    builder.create().mdissmis();
                    upData("FINGERPRINT");
                }

            }
        });
    }

    private void ObtainExtraData() {
        mParamPhoneNumber = getIntent().getStringExtra(PARAM_PHONE_NUMBER);
        mParamIntentCode = getIntent().getIntExtra(PARAM_INTENT_CODE, 0);
    }

    TextView[] tv = new TextView[5];
    private int postion = 0;

    public String getAppVersion() {
        // 获取手机的包管理者
        PackageManager pm = getPackageManager();
        try {
            PackageInfo packInfo = pm.getPackageInfo(getPackageName(), 0);
            return packInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            // 不可能发生.
            return "获取版本号失败";
        }
    }


    private void upData(String type) {
        if (!network()) {
            finish();
        }
        AjaxParams params = new AjaxParams();
        params.put("loginName", sha.getString("mobile", ""));
        params.put("loginType", type);
        params.put("appVersion", getAppVersion());
        try {
            params.put("cipher", URLEncoder.encode(sha.getString("password", ""), "UTF-8"));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
//		try {
//			ToastUtil.showCenterToast(GestureVerifyActivity.this,  URLEncoder.encode(sha.getString("password", ""), "UTF-8"));
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
        VolleryUtil vollery = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
                Log.e("ssssg", jsonObject.toString());
                JSONObject json1 = jsonObject.optJSONObject("data");
                if (jsonObject.optInt("success") == 1) {

                    Editor editor = sha.edit();
                    editor.putString(
                            "token",
                            json1.optString(
                                    "token"));
                    editor.putString(
                            "userId",
                            json1.optString(
                                    "userId"));
                    editor.putString(
                            "photoUrl",
                            json1.optString(
                                    "photoUrl"));
                    editor.putString(
                            "mobile",
                            json1.optString(
                                    "mobile"));
                    editor.putString(
                            "usercode",
                            json1.optString(
                                    "userCode"));
                    editor.putString("loginName", getIntent().getStringExtra("phone"));
                    editor.putInt("islogin", 1);
                    editor.commit();
                    GrowingIO.getInstance().setCS1("user_id", sha.getString("userId", ""));
                    int close = getIntent().getIntExtra("close", 0);

//				if(geturl().contains("/redirect")){
//					Intent intent=new Intent(GestureVerifyActivity.this,MainActivity.class);
//					startActivity(intent);
//					Editor editor2=getShare().edit();
//					editor2.putInt("assets", 0);
//					editor2.commit();
//					return;
//				}
                    if (close == 1) {

                        if (!json1.optString("accountToReveal").equals("")) {
                            mAlertView = new AlertView("", json1.optString("accountToReveal"), null, new String[]{"确定"}, null, GestureVerifyActivity_BeiFen.this, AlertView.Style.Alert, GestureVerifyActivity_BeiFen.this);
                            mAlertView.show();

                            return;
                        }

                        if (getIntent().getIntExtra("web", 0) == 1) {
                            if (getIntent().getIntExtra("assets", 0) == 1) {
                                Intent intent = new Intent();
//							intent.putExtra("resultcode", 1);
                                intent.putExtra("accountToReveal", json1.optString("accountToReveal"));

                                setResult(2, intent);
                                finish();
                                return;
                            }
                            Intent intent = new Intent();
                            intent.putExtra("resultcode", 1);
                            intent.putExtra("accountToReveal", json1.optString("accountToReveal"));
                            setResult(1, intent);
                            Log.e("web", "web");
                            finish();

                        } else {
                            Intent intent = new Intent();
                            intent.putExtra("accountToReveal", json1.optString("accountToReveal"));
                            setResult(1, intent);
                            GestureVerifyActivity_BeiFen.this.finish();
                        }
                        return;

                    }
                  /*  Intent intent = new Intent(GestureVerifyActivity_BeiFen.this, MainActivity.class);
                    startActivity(intent);
                    GestureVerifyActivity_BeiFen.this.finish();*/
                    VolleryUtil3 volleryUtil = new VolleryUtil3() {

                        @Override
                        public void onUpDate(JSONObject jsonObject) {
                            Log.d(jsonObject.toString(), "3333333333333333");

                            // TODO Auto-generated method stub
                            if (jsonObject.optInt("success") == 1) {

                                Intent intent = new Intent(GestureVerifyActivity_BeiFen.this, MainActivity.class);
                                startActivity(intent);
                                GestureVerifyActivity_BeiFen.this.finish();
                            } else {
                                if (jsonObject.optString("comment").equals("please login")) {
//						Editor ed=sha.edit();
//						ed.putInt("islogin", 0);
//						ed.commit();
                                    Log.e("login", jsonObject.toString());
                                    startActivity(new Intent(GestureVerifyActivity_BeiFen.this, V6LoginActivity.class));
                                    GestureVerifyActivity_BeiFen.this.finish();

                                } else {
//                            Toast.makeText(MainActivity.this, jsonObject.optString("comment"), 2000).show();
                                }
                            }

                        }

                        @Override
                        public void onError() {
                            // TODO Auto-generated method stub

                        }
                    };


                    volleryUtil.setHeaders("token", sha.getString("token", ""));
                    volleryUtil.setRequestMethod(0);
                    volleryUtil.execute(GestureVerifyActivity_BeiFen.this, Constant.URL + "/api/v5/user/accountCenter", "");


                } else {
                    if (!json1.optString("accountToReveal").equals("")) {
                        mAlertView = new AlertView("", json1.optString("accountToReveal"), null, new String[]{"确定"}, null, GestureVerifyActivity_BeiFen.this, AlertView.Style.Alert, GestureVerifyActivity_BeiFen.this);
                        mAlertView.show();

                        return;
                    }

                    Intent intent = new Intent(GestureVerifyActivity_BeiFen.this, V6LoginActivity.class);
                    startActivity(intent);
//						}
                    GestureVerifyActivity_BeiFen.this.finish();

                }

            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub
                GestureVerifyActivity_BeiFen.this.finish();
            }
        };
        vollery.setHeaders("appVersion", getAppVersion());
        vollery.setHeaders("token", sha.getString("token", ""));
        vollery.setHeaders("deviceId", getdeviceId());
        vollery.setHeaders("client", "android");
     /*   if (getdevice_token().equals("")) {
            vollery.setHeaders("deviceToken", getdeviceId());
        } else {
            vollery.setHeaders("deviceToken", getdevice_token());

        }*/
        if (getdevice_token().equals("")) {
            vollery.setHeaders("deviceToken", getdevice_token());
        } else {
            vollery.setHeaders("deviceToken", getdevice_token());

        }
        vollery.setHeaders("mobileType", getDeviceType());
        vollery.setRequestMethod(1);
        vollery.setShow(true);
        vollery.execute(this, Constant.URL + "/api/v6/login/app?",
                params.toString());
    }

    private void setUpViews() {
        mTopLayout = (RelativeLayout) findViewById(R.id.top_layout);
        mTextTitle = (TextView) findViewById(R.id.text_title);
        mTextCancel = (TextView) findViewById(R.id.text_cancel);
//		mImgUserLogo = (ImageView) findViewById(R.id.user_logo);
        sha = getSharedPreferences("config", MODE_PRIVATE);
        user_logo = (RoundImageView) findViewById(R.id.user_logo);
        text_welcome = (TextView) findViewById(R.id.text_welcome);
        mTextPhoneNumber = (TextView) findViewById(R.id.text_phone_number);
        mTextTip = (TextView) findViewById(R.id.text_tip);
        mGestureContainer = (FrameLayout) findViewById(R.id.gesture_container);
        mTextForget = (TextView) findViewById(R.id.text_forget_gesture);
        mTextOther = (TextView) findViewById(R.id.text_other_account);
        mTextTip.setText("请绘制手势密码");
        if (sha.getString("photoUrl", "").equals("") || sha.getString("photoUrl", "").equals("null")) {
            if (getSex().equals("女")) {
                user_logo.setImageBitmap(BitmapUtils.readBitMap(GestureVerifyActivity_BeiFen.this, R.drawable.img_girl));
            } else {
                user_logo.setImageBitmap(BitmapUtils.readBitMap(GestureVerifyActivity_BeiFen.this, R.drawable.img_boy));
            }


        } else {
//			BbtApplication.getInstance().imageLoader.loadImageSync(sha.getString("photoUrl", ""),BbtApplication.getInstance().displayImageOptions(R.drawable.img_girl);
            if (sha.getString("fileicon", "").equals("")) {
                Picasso.with(GestureVerifyActivity_BeiFen.this).load(sha.getString("photoUrl", "")).error(R.drawable.img_girl).into(user_logo);
            } else {
                user_logo.setImageBitmap(getSdBitmap(sha.getString("fileicon", "")));
            }
//            handler.sendMessage(message);
//						getBitmap(sha.getString("photoUrl", ""));
//			BbtApplication.getInstance().display(), user_logo);
        }
        if (sha.getString("userNameText", "").equals("") || sha.getString("userNameText", "").equals("null")) {
            text_welcome.setText(sha.getString("mobile", "").substring(0, 3) + "****" + sha.getString("mobile", "").substring(7, sha.getString("mobile", "").length()));
        } else {
            text_welcome.setText("欢迎您･" + sha.getString("userNameText", ""));
        }
//		String mobile=getShare().getString("mobile", "");
//		String maskNumber=mobile.substring(0, 3)+"****"+mobile.substring(7, mobile.length());
//		mTextPhoneNumber.setText(maskNumber);

        // ��ʼ��һ����ʾ�������viewGroup
        mGestureContentView = new GestureContentView(this, true, sha.getString(sha.getString("mobile", "123456"), "123456"),
                new GestureCallBack() {

                    @Override
                    public void onGestureCodeInput(String inputCode) {

                    }

                    @Override
                    public void checkedSuccess() {
                        mGestureContentView.clearDrawlineState(0L);
                        Toast.makeText(GestureVerifyActivity_BeiFen.this, "密码正确", 1000).show();
                        if (getIntent().getIntExtra("update", 0) == 1) {
                            Intent intent = new Intent(GestureVerifyActivity_BeiFen.this, GestureEditActivity.class);

                            intent.putExtra("update", 1);
                            upData("GESTURES");
//                            startActivity(intent);
//                            GestureVerifyActivity.this.finish();

                        } else {

                            upData("GESTURES");

//			    new Handler().postDelayed(new Runnable(){    
//			        public void run() {    
//			        //execute the task    
//			        	GestureVerifyActivity.this.finish();
//			        }    
//			     },2000);   

                        }
                    }

                    @Override
                    public void checkedFail() {
                        error++;
                        mTextTip.setVisibility(View.VISIBLE);

                        if (error == 5) {
                            mTextTip.setText(Html.fromHtml("<font color='#E55835'>密码错误5次,请重新登录</font>"));
                        } else {
                            mTextTip.setText(Html.fromHtml("<font color='#E55835'>错误次数" + error + "次，" + "您还可以输入" + (5 - error) + "次</font>"));
                        }
                        mGestureContentView.clearDrawlineState(1000L);
                        // 左右移动动画
                        Animation shakeAnimation = AnimationUtils.loadAnimation(GestureVerifyActivity_BeiFen.this, R.anim.shake);
                        mTextTip.startAnimation(shakeAnimation);
                        if (error == 5) {
                            Editor editor = sha.edit();

                            editor.commit();
                            Intent intent = new Intent(GestureVerifyActivity_BeiFen.this, V6LoginActivity.class);
                            editor.putString(sha.getString("mobile", "123456"), "");
                            editor.putString("token", "");
                            editor.commit();
                            intent.putExtra("close", 1);
                            startActivity(intent);
                            GestureVerifyActivity_BeiFen.this.finish();
                        }

                    }
                });
        // �������ƽ�����ʾ���ĸ���������
        mGestureContentView.setParentView(mGestureContainer);
    }

    private void setImmersionStatus() {
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        return false;
    }

    public void getBitmap(final String url) {

        new Thread() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                super.run();

                try {
                    Bitmap bm = null;

                    URL iconUrl = new URL(url);
                    URLConnection conn = iconUrl.openConnection();
                    HttpURLConnection http = (HttpURLConnection) conn;

                    int length = http.getContentLength();

                    conn.connect();
                    // 获得图像的字符流
                    InputStream is = conn.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is, length);
                    bm = BitmapFactory.decodeStream(bis);
                    Message message = new Message();
                    message.obj = bm;
                    message.what = 0;
                    handler.sendMessage(message);

                    bis.close();
                    is.close();// 关闭流

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("转换异常", e.toString());
                }
            }
        }.start();


    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {


            user_logo.setImageBitmap((Bitmap) msg.obj);


        }

        ;
    };

    private void setUpListeners() {
        mTextCancel.setOnClickListener(this);
        mTextForget.setOnClickListener(this);
        mTextOther.setOnClickListener(this);
    }

    private String getProtectedMobile(String phoneNumber) {
        if (TextUtils.isEmpty(phoneNumber) || phoneNumber.length() < 11) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        builder.append(phoneNumber.subSequence(0, 3));
        builder.append("****");
        builder.append(phoneNumber.subSequence(7, 11));
        return builder.toString();
    }

    public String getDeviceType() {
        Build build = new Build();
        return build.MODEL;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_cancel:
                this.finish();
                break;
            case R.id.text_forget_gesture:
                Editor editor = sha.edit();
                editor.putString(sha.getString("mobile", "123456"), "");
                editor.putString("token", "");

                editor.commit();
                Intent intent = new Intent(GestureVerifyActivity_BeiFen.this, V6LoginActivity.class);
                startActivity(intent);
                GestureVerifyActivity_BeiFen.this.finish();
                break;
            case R.id.text_other_account:

                Intent intent2 = new Intent(GestureVerifyActivity_BeiFen.this, V6LoginActivity.class);
                Editor editor2 = sha.edit();

                editor2.putString("token", "");
                editor2.putString("mobile", "");
                editor2.commit();
                startActivity(intent2);
                GestureVerifyActivity_BeiFen.this.finish();
                break;
        }
    }

    public void showToast(String name) {
        Toast.makeText(GestureVerifyActivity_BeiFen.this, name, Toast.LENGTH_SHORT).show();
    }

    private Bitmap getSdBitmap(String path) {
        File mFile = new File(path);
        Bitmap bitmap;
        //若该文件存在
        if (mFile.exists()) {
//	        	LogUtils.e(GestureVerifyActivity.this.this, "sd卡图片存在");
            bitmap = BitmapFactory.decodeFile(path);
            return bitmap;
        } else {
            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img_girl);
        }
        return bitmap;
    }

    @Override
    public void onDismiss(Object o) {

    }

    @Override
    public void onItemClick(Object o, int position) {
        Intent intent = new Intent(GestureVerifyActivity_BeiFen.this, V6LoginActivity.class);
        startActivity(intent);
        GestureVerifyActivity_BeiFen.this.finish();
    }
}
